#pragma once

#include <string>
#include <vector>

bool is_start_byte(char byte)
{
	//Checks if the character begins a UTF-8 sequence.
	unsigned char code = (unsigned char)byte;
	if (code < 0b10000000 || code >= 0b11000000)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int fol_bytes(char byte)
//Returns the amount of bytes immediately following a given UTF-8 byte.
{
	unsigned char code = (unsigned char)byte;
	if (!is_start_byte(byte))
	{
		return 0;
	}
	else if (code < 0b10000000)
	{
		return 0;
	}
	else if (code < 0b11100000)
	{
		return 1;
	}
	else if (code < 0b11110000)
	{
		return 2;
	}
	else
	{
		return 3;
	}
}

int u_length(std::string str)
//Returns the length of a UTF-8-containing string in meaningful characters.
{
	int result = 0;
	for (int i = 0; i < str.size(); i++)
	{
		if(is_start_byte(str[i]))
		{
			result++;
		}
	}
	return result;
}

std::string u_at (std::string str, int where)
//Returns a one-UTF8-letter-substring at a position in an imaginary one-byte-width string.
{
	std::vector<int> positions;
	for (int i = 0; i < str.size(); i++)
	{
		if (is_start_byte(str[i]))
		{
			positions.push_back(i);
		}
	}
	return str.substr(positions[where], 1+fol_bytes(str[positions[where]]));
}

std::string u_substr (std::string str, int begin, int length)
{
	std::string result;
	for (int i = 0; i < length; i++)
	{
		result += u_at(str, begin+i);
	}
	return result;
}
	
